import React, { useState } from 'react';
import { Form, message, ConfigProvider } from 'antd';
import cn from 'classnames';
import { FormContainer } from '@/components/UserForm';
import styles from '../index.less';
import { jsonFormSchool, jsonFormTrain } from '../jsonForm';

let initSchoolKey = 0;
let initTrainKey = 0;
const Form3 = ({ form, getComponent, entryUser, returnValue, getArrKeys }) => {
    const { getFieldDecorator } = form;
    const [schoolKeys, setSchoolKeys] = useState([initSchoolKey]);
    const [trainKeys, setTrainKeys] = useState([initTrainKey]);
    const [removeSchoolIds, setRemoveSchoolIds] = useState([]);
    const [removeTrainIds, setRemoveTrainIds] = useState([]);

    getFieldDecorator('schoolKeys', { initialValue: [0] }); // 用于保存keys的字段，方便外面可以取之到keys
    getFieldDecorator('trainKeys', { initialValue: [0] });
    getFieldDecorator('removeSchoolIds', { initialValue: [] });
    getFieldDecorator('removeTrainIds', { initialValue: [] });

    const computedValidLength = (removedIdsStr, keys) => {
        const removeId = form.getFieldValue(removedIdsStr);
        return keys.length - removeId.length;
    };

    const showErrorMessage = () => {
        message.error('至多添加10个');
    };

    // eslint-disable-next-line consistent-return
    const addFormList = type => {
        if (type === 'school') {
            if (computedValidLength('removeSchoolIds', schoolKeys) >= 10) {
                return showErrorMessage();
            }
            initSchoolKey += 1;
            schoolKeys.push(initSchoolKey);
            setSchoolKeys([...schoolKeys]);
            form.setFieldsValue({
                schoolKeys
            });
        } else if (type === 'train') {
            if (computedValidLength('removeTrainIds', trainKeys) >= 10) {
                return showErrorMessage();
            }
            initTrainKey += 1;
            trainKeys.push(initTrainKey);
            setTrainKeys([...trainKeys]);
            form.setFieldsValue({
                trainKeys
            });
        }
    };
    // 删除组件
    const deleteGroup = (type, targetKey, deleteId) => {
        let newKeys = [];
        if (type === 'school') {
            if (deleteId) {
                const removeId = [...removeSchoolIds, deleteId];
                setRemoveSchoolIds(removeId);
                form.setFieldsValue({
                    removeSchoolIds: removeId
                });
                return;
            }
            newKeys = schoolKeys.filter(key => key !== targetKey);
            setSchoolKeys([...newKeys]);
            form.setFieldsValue({
                schoolKeys: newKeys
            });
        } else if (type === 'train') {
            if (deleteId) {
                const removeId = [...removeTrainIds, deleteId];
                setRemoveTrainIds(removeId);
                form.setFieldsValue({
                    removeTrainIds: removeId
                });
                return;
            }
            newKeys = trainKeys.filter(key => key !== targetKey);
            setTrainKeys([...newKeys]);
            form.setFieldsValue({
                trainKeys: newKeys
            });
        }
    };

    // 渲染表单组件
    const renderFormItem = type => {
        let arr = [];
        let keys = [];
        let value = [];
        let removeIds = [];
        if (type === 'school') {
            arr = jsonFormSchool;
            keys = schoolKeys;
            value = entryUser.schoolDTOList || [];
            removeIds = removeSchoolIds;
        } else if (type === 'train') {
            arr = jsonFormTrain;
            keys = trainKeys;
            value = entryUser.trainDTOList || [];
            removeIds = removeTrainIds;
        }

        return keys
            .filter(key => !removeIds.includes(value[key] && value[key].id))
            .map(key => (
                <div className={styles.block} key={type + key}>
                    {key !== 0 ? (
                        <i
                            className={cn(styles.del, 'iconfont icongms_list_icon_fail_default')}
                            onClick={() => {
                                deleteGroup(type, key, value[key] && value[key].id);
                            }}
                        />
                    ) : (
                        ''
                    )}
                    <FormContainer>
                        {arr.map(list => (
                            <Form.Item label={list.label} key={list.fileName}>
                                {getFieldDecorator(`${list.fileName}_${key}`, {
                                    rules: list.rules,
                                    initialValue: value[key] && returnValue(list.fileName, value[key])
                                })(
                                    getComponent(
                                        list.type,
                                        list.code,
                                        `${list.fileName}_${key}`,
                                        list.placeholder,
                                        value[key] && value[key].areaCode
                                    )
                                )}
                            </Form.Item>
                        ))}
                    </FormContainer>
                </div>
            ));
    };

    React.useEffect(() => {
        if (entryUser.schoolDTOList && entryUser.schoolDTOList.length) {
            initSchoolKey = entryUser.schoolDTOList.length > 0 ? entryUser.schoolDTOList.length - 1 : 0;
            setSchoolKeys(getArrKeys(entryUser.schoolDTOList));
            form.setFieldsValue({
                schoolKeys: getArrKeys(entryUser.schoolDTOList)
            });
        }
        if (entryUser.trainDTOList && entryUser.trainDTOList.length) {
            initTrainKey = entryUser.trainDTOList.length > 0 ? entryUser.trainDTOList.length - 1 : 0;
            setTrainKeys(getArrKeys(entryUser.trainDTOList));
            form.setFieldsValue({
                trainKeys: getArrKeys(entryUser.trainDTOList)
            });
        }
    }, [entryUser]);
    return (
        <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
            <div className="family">
                <div className={styles.title} id="form3-1">
                    教育经历
                </div>
                {renderFormItem('school')}
                <div
                    className={styles.add}
                    onClick={() => {
                        addFormList('school');
                    }}
                >
                    +添加教育经历
                </div>
            </div>
            <div className="work">
                <div className={styles.title} id="form3-2">
                    培训经历
                </div>
                {renderFormItem('train')}
                <div
                    className={styles.add}
                    onClick={() => {
                        addFormList('train');
                    }}
                >
                    +添加培训经历
                </div>
            </div>
            {/* <div className={styles.btnItem}>
                <Button
                    onClick={() => {
                        onNext('1');
                    }}
                >
                    上一步
                </Button>
                <Button
                    type="primary"
                    onClick={() => {
                        submit();
                    }}
                >
                    下一步
                </Button>
            </div> */}
        </ConfigProvider>
    );
};
export default Form3;
